package com.yami.shop.mystery.multishop.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.yami.shop.bean.event.ActivityRemoveChangeStatusEvent;
import com.yami.shop.bean.model.ActivityReceiveRecord;
import com.yami.shop.bean.model.Product;
import com.yami.shop.common.bean.PageDTO;
import com.yami.shop.common.bean.PageVO;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.mystery.common.dto.ActivityPresellDto;
import com.yami.shop.mystery.common.model.ActivityPresell;
import com.yami.shop.mystery.common.model.ActivityProd;
import com.yami.shop.mystery.common.service.ActivityPresellService;
import com.yami.shop.mystery.common.service.ActivityProdService;
import com.yami.shop.mystery.common.service.ActivityReceiveRecordService;
import com.yami.shop.mystery.common.vo.ActivityPresellPageVo;
import com.yami.shop.security.common.util.AuthUserContext;
import com.yami.shop.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 活动
 *
 * @author wxf
 * @date 2023/4/12 11:02
 */
@RestController
@RequestMapping("/activity/activityPresell")
@Tag(name="活动接口")
public class ActivityPresellController {

    @Autowired
    private ActivityPresellService presellService;

    @Autowired
    private ActivityProdService prodService;

    @Autowired
    private ProductService productService;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private ActivityReceiveRecordService activityReceiveRecordService;

    @GetMapping("/list")
    @Operation(summary = "活动分页列表")
    public ServerResponseEntity<PageVO<ActivityPresellDto>> pageList(ActivityPresellPageVo vo,PageDTO pageDTO) {
        // 根据产品查询时，先去模糊匹配产品 获取id后 再通过主表使用in查记录
        if (StrUtil.isNotEmpty(vo.getProdName())) {
            List<Product> products = productService.list(new LambdaQueryWrapper<Product>().like(Product::getProdName, vo.getProdName()));
            List<Long> longs = products.stream().map(p -> p.getProdId()).collect(Collectors.toList());
            vo.setSpuId(longs);
        }
        vo.setShopId(AuthUserContext.get().getShopId());
        PageVO<ActivityPresellDto> page = presellService.pageList(pageDTO,vo);
        return ServerResponseEntity.success(page);
    }

    @PostMapping("/save")
    @Operation(summary = "新增/修改活动")
    public ServerResponseEntity<Void> saveOrUpdate(@RequestBody ActivityPresellDto dto) {
        if(ObjectUtil.isEmpty(dto.getProds())){
            throw new YamiShopBindException("活动商品不能为空");
        }
        // 默认修改 为 开启状态
        dto.setStatus(0);
        presellService.saveOrUpdate(dto);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除活动")
    public ServerResponseEntity<Void> deleteBrand(@RequestParam Long id) {
        presellService.removeIds(Lists.newArrayList(id));
        return ServerResponseEntity.success();
    }

    @GetMapping("/info/{id}")
    @Operation(summary = "获取活动详细信息")
    @Parameter(name = "id", description = "活动主键", required = true)
    public ServerResponseEntity<ActivityPresellDto> info(@PathVariable("id") Long id) {
        ActivityPresellDto coupon = presellService.detail(id);
        return ServerResponseEntity.success(coupon);
    }

    @PostMapping("waterSoldNum")
    @Operation(summary = "修改报名注水量")
    public ServerResponseEntity<Void> waterSoldNum(@RequestBody ActivityProd activityProd) {
        prodService.updateWaterSoldNum(activityProd);
        return ServerResponseEntity.success();
    }

    @GetMapping("getList")
    @Operation(summary = "获取活动时间内的活动列表")
    public ServerResponseEntity<List<ActivityPresellDto>> getList(String activityIds) {
        List<ActivityPresellDto> list = presellService.getList(activityIds);
        return ServerResponseEntity.success(list);
    }

    @GetMapping("/offActivity")
    @Operation(summary = "关闭活动")
    @Parameter(name = "id", description = "活动主键", required = true)
    public ServerResponseEntity<Void> offActivity(Long activityId) {

        ActivityPresell presell = presellService.getById(activityId);
        // 设置活动为失效
        ActivityPresell updateDB = new ActivityPresell();
        updateDB.setId(presell.getId());
        updateDB.setStatus(4);
        presellService.updateById(updateDB);

        List<ActivityProd> prodIds = prodService.list(new LambdaQueryWrapper<ActivityProd>()
                .eq(ActivityProd::getIsDel, 0).eq(ActivityProd::getActivityId, activityId));
        List<Long> pids = prodIds.stream().filter(a -> a.getProdId() != -1).map(a -> a.getProdId()).distinct().collect(Collectors.toList());

        Integer status = 0;
        if ("3".equals(presell.getActivityType())) {
            status = 0;
        }
        if("4".equals(presell.getActivityType()) && presell.getBlindType() == 1){
            presell.setActivityType("5");
            eventPublisher.publishEvent(new ActivityRemoveChangeStatusEvent(0,status, pids, presell.getActivityType()));
            return ServerResponseEntity.success();
        }
        return ServerResponseEntity.success();
    }

    @GetMapping("/zeropage")
    @Operation(summary =  "零元购领取记录", description = "零元购领取记录")
    public ServerResponseEntity<PageVO<ActivityReceiveRecord>> zeroPage(PageDTO pageDTO, @Param("prodName") String prodName, @Param("userName")String userName, @Param("userMobile")String userMobile,@Param("status") String status) {
        Long shopId = AuthUserContext.get().getShopId();
        return ServerResponseEntity.success(activityReceiveRecordService.zeroPage(pageDTO, prodName,userName,userMobile,status,shopId));
    }


    @PostMapping("/saveOrUpdateNewcomerRewards")
    @Operation(summary = "新增/修改新人奖励活动")
    public ServerResponseEntity<Void> saveOrUpdateNewcomerRewards(@RequestBody ActivityPresellDto dto) {
        if(ObjectUtil.isEmpty(dto.getProds())){
            throw new YamiShopBindException("活动商品不能为空");
        }
        // 默认修改 为 开启状态
        dto.setStatus(0);
        presellService.saveOrUpdateNewcomerRewards(dto);
        return ServerResponseEntity.success();
    }


}
